/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.lettuce.core.dynamic.annotation.Param;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.domain.Courseandteach;
import me.zhengjie.modules.system.domain.Teach;
import me.zhengjie.modules.system.domain.Teachandteacher;
import me.zhengjie.modules.system.domain.Teachtype;
import me.zhengjie.modules.system.domain.dto.CourseandteachDto;
import me.zhengjie.modules.system.domain.vo.CourseandteachVo;
import me.zhengjie.modules.system.service.*;
import me.zhengjie.modules.system.domain.vo.TeachQueryCriteria;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.zhengjie.utils.PageResult;

/**
* @author shitou
* @date 2024-04-21
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "教材管理")
@RequestMapping("/api/teach")
public class TeachController {

    private final TeachService teachService;

    private final TeachtypeService teachTypeService;

    private final TeachandteacherService teachandteacherService;

    private final CourseandteachService courseorService;


    private final CourseandteachService courseandteachService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
//    @PreAuthorize("@el.check('teach:list')")
    public void exportTeach(HttpServletResponse response, TeachQueryCriteria criteria) throws IOException {
        teachService.download(teachService.queryAll(criteria), response);
    }
    //获取课程教材详情
    @GetMapping("/queryTeachMsg")
    @Log("查询课程教材")
    @ApiOperation("查询课程教材")
    public ResponseEntity<Teach> queryTeachMsg(@RequestParam("teachId") Integer teachId) {

        return new ResponseEntity<>(teachService.getById(teachId),HttpStatus.OK);
    }
//    CourseAndTeach
    @GetMapping("/queryCourseTeach")
    @Log("查询课程教材")
    @ApiOperation("查询课程教材")
    public ResponseEntity<CourseandteachVo> queryCourseTeach(@RequestParam("courseid") Integer courseId) {

        return new ResponseEntity<>(teachService.queryCourseTeach(courseId),HttpStatus.OK);
    }

    @GetMapping
    @Log("查询教材")
    @ApiOperation("查询教材")
//    @PreAuthorize("@el.check('teach:list')")
    public ResponseEntity<PageResult<Teach>> queryTeach(TeachQueryCriteria criteria, Page<Object> page){


        PageResult<Teach> pageList = teachService.queryAll(criteria,page);
        if(pageList.getContent().size()==0){
            return new ResponseEntity<>(pageList,HttpStatus.OK);
        }
        List<Integer> list = new ArrayList<>();

        List<Long> list2 = new ArrayList<>();
        for(Teach teach : pageList.getContent()){
            list.add(teach.getTeachtypeid());
            list2.add(teach.getId());
        }
        List<Teachtype>  teachtypeList =  teachTypeService.listByIds(list);


        List<Teachandteacher>  teachandteacherList = teachandteacherService.queryAllBySchoolId(list2);

        for(Teach teach:pageList.getContent()){
            List<Long> list3 = new ArrayList<>();
            for(Teachtype teachtype :teachtypeList){
                if(Objects.equals(String.valueOf(teachtype.getId()), String.valueOf(teach.getTeachtypeid()))){
                    teach.setTeachtypename(teachtype.getName());
                }
            }

            for(Teachandteacher teachandteacher:teachandteacherList){
                if(Objects.equals(String.valueOf(teach.getId()), String.valueOf(teachandteacher.getTeachid()))){
                    list3.add(teachandteacher.getUserid());
                }
            }
            teach.setTeacherIds(list3);
        }
        return new ResponseEntity<>(pageList,HttpStatus.OK);
    }

    @GetMapping("/queryTeacherAll")
    @Log("查询教材")
    @ApiOperation("查询教材")
    //    @PreAuthorize("@el.check('teach:list')")
    public ResponseEntity<PageResult<Teach>> queryTeacherAll(TeachQueryCriteria criteria, Page<Object> page){
        return new ResponseEntity<>(teachService.queryTeacherAll(criteria,page),HttpStatus.OK);
    }

    //查询用户可编辑 和共享的教材
    @GetMapping("/queryViewTeach")
    @ApiOperation("查看教材")
    public ResponseEntity<PageResult<Teach>> queryViewTeach(@Param("courseId") Integer courseId, Page<Object> page){

        return new ResponseEntity<>(teachService.queryViewTeach(courseId,page),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增教材")
    @ApiOperation("新增教材")
//    @PreAuthorize("@el.check('teach:add')")
    public ResponseEntity<Object> createTeach(@Validated @RequestBody Teach resources){

        return new ResponseEntity<>(teachService.create(resources),HttpStatus.OK);
    }

    @PostMapping("/bindCourseTeach")
    @Log("查询课程教材")
    @ApiOperation("查询课程教材")
    public ResponseEntity<Object> bindCourseTeach(@Validated @RequestBody List<Courseandteach> resources) {

        if(resources.isEmpty()){
            return new ResponseEntity<>("参数不能为空",HttpStatus.OK);
        }
        //获取现在的课程教材id
        List<Long> currentTeachIds = new ArrayList<>();
        for(Courseandteach courseandteach:resources){
            currentTeachIds.add(courseandteach.getTeachid());
        }
        //获取之前的课程教材id
        Long courseId = resources.get(0).getCourseid();
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("courseid",courseId);
        List<Courseandteach> courseandteachList= courseandteachService.list(queryWrapper);
        List<Long> courseandteachIds = new ArrayList<>();

        //获取删除id
        List<Integer> deleteIds = new ArrayList<>();

        for(Courseandteach courseandteach:courseandteachList){

            if(!containsElement(currentTeachIds,courseandteach.getTeachid())){
                deleteIds.add(Integer.valueOf(Math.toIntExact(courseandteach.getTeachid())));
            } else {
                courseandteachIds.add(courseandteach.getTeachid());
            }
        }
        if(!deleteIds.isEmpty()){
            courseandteachService.deleteAll(deleteIds);
        }


        for(Courseandteach courseandteach:resources){
            if(!containsElement(courseandteachIds,courseandteach.getTeachid())){
                courseandteachService.save(courseandteach);
            } else if(containsElement(courseandteachIds,courseandteach.getTeachid())){
                System.out.println(courseandteach);

                QueryWrapper queryWrapper1 = new QueryWrapper<>()
                        .eq("courseid",courseandteach.getCourseid())
                        .eq("teachid",courseandteach.getTeachid());
                Courseandteach courseandteach1 = courseandteachService.getOne(queryWrapper1);
                courseandteachService.update(courseandteach1);
            }

        }

        //获取所有课程教材 并绑定给课程所在班级的学生
        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("courseid",courseId);
        List<Courseandteach> courseandteachList2 = courseandteachService.list(queryWrapper);

        List<Long> teachIdsList = new ArrayList<>();
        for(Courseandteach courseandteach:courseandteachList2){
            teachIdsList.add(courseandteach.getTeachid());
        }

        return new ResponseEntity<>(null,HttpStatus.OK);
    }

    public boolean containsElement(List<Long> array, Long target) {
        for (int i = 0; i < array.size(); i++) {
            if (array.get(i) ==  target) {
                return true;
            }
        }
        return false;
    }

    @PutMapping
    @Log("修改教材")
    @ApiOperation("修改教材")
//    @PreAuthorize("@el.check('teach:edit')")
    public ResponseEntity<Object> updateTeach(@Validated @RequestBody Teach resources){
        teachService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

//    @PutMapping("/updateTeachAudit")
//    @Log("修改教材审核")
//    @ApiOperation("修改教材审核")
//    public ResponseEntity<Object> updateTeachAudit(@Validated @RequestBody Teach resources){
//
//        teachService.updateTeachAudit(resources);
//        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
//    }

    @DeleteMapping
    @Log("删除教材")
    @ApiOperation("删除教材")
//    @PreAuthorize("@el.check('teach:del')")
    public ResponseEntity<Object> deleteTeach(@RequestBody List<Integer> ids) {
        teachService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}